package com.xxx.system.service.Impl;

import com.github.pagehelper.PageHelper;
import com.xxx.system.domain.Menu;
import com.xxx.system.mapper.MenuMapper;
import com.xxx.system.query.MenuQuery;
import com.xxx.system.service.menuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MenuServiceImpl implements menuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> findAll() {
        return menuMapper.findAll();
    }

    @Override
    public Menu findOne(Long id) {
        return menuMapper.findOne(id);
    }

    @Override
    public List<Menu> queryPage(MenuQuery menuQuery) {
        PageHelper.startPage(menuQuery.getCurrentPage(),menuQuery.getPageSize());
        return menuMapper.queryPage(menuQuery);
    }

    @Override
    public void addMenu(Menu menu) {
        menuMapper.addMenu(menu);
    }

    @Override
    public void updateMenu(Menu menu) {
        menuMapper.updateMenu(menu);
    }

    @Override
    public void deleteMenuById(Long id) {
        menuMapper.deleteMenuById(id);
    }

    @Override
    public void deleteMenuByIds(Long[] ids) {
        menuMapper.deleteMenuByIds(ids);
    }

    public List<Menu> getMenuTree(){
        List<Menu> menuTree = new ArrayList<>();
        List<Menu> menus = menuMapper.findAll();
        Map<Long,Menu> map = new HashMap<>();
        for (Menu menu : menus) {
            map.put(menu.getId(),menu);
        }
        for (Menu menu : menus) {
            if(menu.getParentId() ==null){
                menuTree.add(menu);
            }else{
                Long parenId = menu.getParentId();
                Menu parentMenu = map.get(parenId);
                if (parentMenu!=null){
                     List<Menu> children = parentMenu.getChildren();
                     children.add(menu);
                }
            }
        }
        return menuTree;
    }
}
